﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace mscook.core.services
{
    public class FormAuthenticationService:IFormAuthenticationService
    {
        #region IFormAuthenticationService 成员

        public FormsAuthenticationTicket populateFormAuthCookie(bool isPersistent, string userID, string userType,HttpContextBase httpContext)
        {
            DateTime expiredTime;
            if (isPersistent)
            {
                expiredTime = DateTime.Now.AddMonths(10);
            }
            else
            {
                expiredTime = DateTime.Now.AddMinutes(10);
            }
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                               userID,
                               DateTime.Now,
                               expiredTime,
                               isPersistent,
                               userType, //CompanyID
                               FormsAuthentication.FormsCookiePath);
            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);//加密序列化验证票为字符串
            //生成Cookie
            if (isPersistent)
            {
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                {
                    HttpOnly = true,
                    Path = ticket.CookiePath,

                    Expires = expiredTime,
                    Domain = FormsAuthentication.CookieDomain,
                };
                httpContext.Response.Cookies.Add(cookie); //输出Cookie
            }
            else
            {
                //2012-12-30 basilwang FormsAuthentication.RedirectFromLoginPage will call SetAuthCookie,so we put SetAuthCookie here.
                //and we don't use FormsAuthentication.RedirectFromLoginPage anymore
                FormsAuthentication.SetAuthCookie(userID, false);
            }

            return ticket;
        }

        #endregion
    }
}
